﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;

namespace Me.Prettyprint.Cassandra.Utils
{
    /// <summary>
    /// Using extension methods to make it easy to shuffle a generic list
    /// </summary>
    public static class ShuffleExtension
    {
        public static void Shuffle<T>(this IList<T> items)
        {
            var randomGenerator = new RNGCryptoServiceProvider();
            var itemIndex = items.Count;

            while (itemIndex > 1)
            {
                //Generate a new random number using RNGCryptoServiceProvider since Random sucks
                var box = new byte[1];
                do
                {
                    randomGenerator.GetBytes(box);
                }
                while (!(box[0] < itemIndex * (Byte.MaxValue / itemIndex)));

                var randomIndex = (box[0] % itemIndex);
                itemIndex--;

                //Swap the indexed and random positions
                T value = items[randomIndex];
                items[randomIndex] = items[itemIndex];
                items[itemIndex] = value;
            }
        }
        public static void Shuffle<T>(this List<T> items)
        {
            var randomGenerator = new RNGCryptoServiceProvider();
            var itemIndex = items.Count;

            while (itemIndex > 1)
            {
                //Generate a new random number using RNGCryptoServiceProvider since Random sucks
                var box = new byte[1];
                do
                {
                    randomGenerator.GetBytes(box);
                }
                while (!(box[0] < itemIndex * (Byte.MaxValue / itemIndex)));

                var randomIndex = (box[0] % itemIndex);
                itemIndex--;

                //Swap the indexed and random positions
                T value = items[randomIndex];
                items[randomIndex] = items[itemIndex];
                items[itemIndex] = value;
            }
        }
    }
}
